package at.fhhgb.mc.android.mfb_hgb.activity;

import java.util.List;

import org.apache.http.message.BasicNameValuePair;

import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.support.v7.app.ActionBarActivity;
import at.fhhgb.mc.android.mfb_hgb.R;
import at.fhhgb.mc.android.mfb_hgb.dal.SelectUser;
import at.fhhgb.mc.android.mfb_hgb.model.TaskCaller;
import at.fhhgb.mc.android.mfb_hgb.model.User;

public class SplashScreen extends ActionBarActivity implements TaskCaller {

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_splash_screen);
		getActionBar().hide();

		Handler handler = new Handler();
		handler.postDelayed(new Runnable() {

			@Override
			public void run() {
				// Look for stored Login-Data
				SharedPreferences prefs = getSharedPreferences(getString(R.string.preferences_key), MODE_PRIVATE);
				String username = prefs.getString("username", null);
				String password = prefs.getString("pwd", null);

				// Check stored Login-Data, if one exists
				if (username != null && password != null) {
					new SelectUser(SplashScreen.this).execute(new BasicNameValuePair("Username", username), new BasicNameValuePair("Password", password));
				} else {
					Intent i = new Intent(SplashScreen.this, LoginActivity.class);
					SplashScreen.this.finish();
					startActivity(i);
				}
			}
		}, 1000);
	}

	@Override
	public void onBackgroundTaskCompleted(Object result) {
		Intent i;

		if (result == null || ((List<User>) result).isEmpty()) {
			i = new Intent(this, LoginActivity.class);
		} else {
			i = new Intent(this, OverviewActivity.class);
		}

		finish();
		startActivity(i);
	}

}
